package cn.itcast.session;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "CartServlet", urlPatterns = "/CartServlet")
public class CartServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=utf-8");
        PrintWriter out = resp.getWriter();

        List<CartItem> cart = null;
        boolean purFlag = false;

        HttpSession session = req.getSession(false);
        if (session != null) {
            cart = (List<CartItem>) session.getAttribute("cart");
            if (cart != null && !cart.isEmpty()) {
                purFlag = true;
            }
        }

        if (!purFlag) {
            out.write("对不起！您还没有购买任何商品！<br>");
        } else {
            out.write("您购买的商品有： <br>");
            double totalPrice = 0;
            for (CartItem item : cart) {
                shop shop = item.getCake();
                int quantity = item.getQuantity();
                double price = shop.getPrice();

                out.write(shop.getName() + " (数量: " + quantity + ") <br>");
                totalPrice += price * quantity;
            }
            out.write("总价格: " + String.format("%.2f",totalPrice) + " 元<br>");
        }
    }
}